<template>
  <div class="shiftarrangements">
    <router-link to="/">返回首页</router-link>
    <div class="header">
      <van-button type="primary" @click="startEditing" :disabled="isEditing">
        {{ isEditing ? '编辑中...' : '开始排班' }}
      </van-button>
      <van-button v-if="isEditing" type="success" @click="saveSchedule" style="margin-left: 10px">
        保存排班
      </van-button>
    </div>

    <div class="calendar-container">
      <div class="calendar-header">
        <van-button icon="arrow-left" @click="prevWeek" />
        <h2>{{ currentWeekRange }}</h2>
        <van-button icon="arrow-right" @click="nextWeek" />
      </div>
      <div class="calendar-grid">
        <div class="weekday-header" v-for="day in weekDays" :key="day">
          {{ day }}
        </div>
        <div
          v-for="(day, index) in weekDaysData"
          :key="day.date"
          class="calendar-day"
          :class="{ 'has-shift': day.staff.length > 0, editing: isEditing }"
          @click="handleDayClick(day, index)"
        >
          <div class="date-number">{{ day.date }}</div>
          <div class="staff-list">
            <div v-for="(staff, idx) in day.staff" :key="idx" class="staff-name">
              {{ staff.name }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 人员选择弹窗 -->
    <van-popup v-model:show="showStaffSelector" position="bottom" :style="{ height: '60%' }">
      <div class="popup-header">
        <h3>
          {{ selectedDay ? `${selectedDay.weekday} ${selectedDay.date}日 排班` : '选择排班人员' }}
        </h3>
        <van-icon name="close" @click="showStaffSelector = false" />
      </div>
      <div class="staff-list-container">
        <div
          v-for="staff in allStaff"
          :key="staff.id"
          class="staff-item"
          :class="{ selected: isStaffSelected(staff.id) }"
          @click="toggleStaffSelection(staff)"
        >
          <div class="staff-info">
            <div class="staff-avatar">{{ staff.name.charAt(0) }}</div>
            <div class="staff-details">
              <div class="staff-name">{{ staff.name }}</div>
              <div class="staff-position">{{ staff.position }}</div>
            </div>
          </div>
          <van-checkbox v-model="staff.selected" :checked="isStaffSelected(staff.id)">
            {{ staff.selected ? '已选中' : '选中' }}
          </van-checkbox>
        </div>
      </div>
      <div class="popup-footer">
        <van-button type="primary" block @click="confirmStaffSelection">确定</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { showToast } from 'vant'

// 定义类型
interface Staff {
  id: string
  name: string
  position: string
  selected?: boolean
}

interface WeekDay {
  date: number
  weekday: string
  staff: Staff[]
}

// 常量
const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

// 响应式数据
const isEditing = ref(false)
const showStaffSelector = ref(false)
const currentDate = ref(new Date())
const selectedDay = ref<WeekDay | null>(null)
const selectedDayIndex = ref<number | null>(null)

// 模拟人员数据
const allStaff = ref<Staff[]>([
  { id: '1', name: '张三', position: '前台接待' },
  { id: '2', name: '李四', position: '技术支持' },
  { id: '3', name: '王五', position: '客服专员' },
  { id: '4', name: '赵六', position: '销售人员' },
  { id: '5', name: '钱七', position: '财务专员' },
])

// 计算一周日期数据
const weekDaysData = ref<WeekDay[]>([])

// 计算当前周范围显示文本
const currentWeekRange = computed(() => {
  const firstDay = new Date(currentDate.value)
  const day = firstDay.getDay() || 7 // 将周日从0转为7
  firstDay.setDate(firstDay.getDate() - day + 1) // 设置为周一
  const lastDay = new Date(firstDay)
  lastDay.setDate(firstDay.getDate() + 6)

  const formatDate = (date: Date) => {
    return `${date.getMonth() + 1}月${date.getDate()}日`
  }

  return `${formatDate(firstDay)} - ${formatDate(lastDay)}`
})

// 生成一周日期数据
const generateWeekData = () => {
  const startDate = new Date(currentDate.value)
  const day = startDate.getDay() || 7 // 将周日从0转为7
  startDate.setDate(startDate.getDate() - day + 1) // 设置为周一

  const weekData: WeekDay[] = []

  for (let i = 0; i < 7; i++) {
    const date = new Date(startDate)
    date.setDate(startDate.getDate() + i - 1) // 从周日开始

    // 查找是否有已保存的排班数据
    const savedShift = localStorage.getItem(`shift_${date.toISOString().split('T')[0]}`)
    const staffList = savedShift ? JSON.parse(savedShift) : []

    weekData.push({
      date: date.getDate(),
      weekday: weekDays[date.getDay()] ?? '',
      staff: staffList,
    })
  }

  weekDaysData.value = weekData
}

// 切换到上一周
const prevWeek = () => {
  currentDate.value.setDate(currentDate.value.getDate() - 7)
  generateWeekData()
}

// 切换到下一周
const nextWeek = () => {
  currentDate.value.setDate(currentDate.value.getDate() + 7)
  generateWeekData()
}

// 开始编辑排班
const startEditing = () => {
  isEditing.value = true
  showToast('进入编辑模式，可以选择排班人员')
}

// 处理日期点击
const handleDayClick = (day: WeekDay, index: number) => {
  if (isEditing.value) {
    selectedDay.value = day
    selectedDayIndex.value = index

    // 重置所有人员的选中状态
    allStaff.value.forEach((staff) => {
      staff.selected = day.staff.some((s) => s.id === staff.id)
    })

    showStaffSelector.value = true
  }
}

// 检查人员是否已选中
const isStaffSelected = (staffId: string): boolean => {
  return selectedDay.value?.staff.some((s) => s.id === staffId) || false
}

// 切换人员选中状态
const toggleStaffSelection = (staff: Staff) => {
  staff.selected = !staff.selected
}

// 确认人员选择
const confirmStaffSelection = () => {
  if (selectedDayIndex === null || !selectedDay) return

  const selectedStaff = allStaff.value
    .filter((staff) => staff.selected)
    .map((staff) => ({ id: staff.id, name: staff.name, position: staff.position }))

  // 更新选中日期的排班数据
  if (selectedDayIndex.value !== null) {
    if (selectedDayIndex.value !== null && weekDaysData.value[selectedDayIndex.value]) {
      const dayData = weekDaysData.value[selectedDayIndex.value]
      if (dayData) {
        dayData.staff = selectedStaff
      }
    }
  }

  // 保存到本地存储
  const date = new Date(currentDate.value)
  const day = date.getDay() || 7
  date.setDate(date.getDate() - day + 1) // 设置为周一
  // 确保selectedDayIndex不为null
  const dayIndex = selectedDayIndex.value ?? 0
  date.setDate(date.getDate() + dayIndex - 1) // 调整到选中的日期

  localStorage.setItem(`shift_${date.toISOString().split('T')[0]}`, JSON.stringify(selectedStaff))

  showStaffSelector.value = false
  showToast('排班已更新')
}

// 保存排班
const saveSchedule = () => {
  isEditing.value = false
  showToast('排班已保存')
}

// 页面挂载时生成一周数据
onMounted(() => {
  generateWeekData()
})
</script>

<style scoped>
.shiftarrangements {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.header h1 {
  margin: 0;
  color: #333;
}

.calendar-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.calendar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.calendar-header h2 {
  margin: 0;
  font-size: 18px;
  color: #666;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 10px;
}

.weekday-header {
  text-align: center;
  padding: 10px;
  font-weight: bold;
  color: #666;
  background: #f5f5f5;
  border-radius: 4px;
}

.calendar-day {
  background: #fafafa;
  border: 2px solid transparent;
  border-radius: 8px;
  padding: 10px;
  min-height: 120px;
  cursor: default;
  transition: all 0.3s;
}

.calendar-day:hover {
  background: #f0f0f0;
}

.calendar-day.editing {
  cursor: pointer;
}

.calendar-day.editing:hover {
  border-color: #42b983;
  background: #e6f7f0;
}

.calendar-day.has-shift {
  background: #e6f7f0;
}

.date-number {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.staff-list {
  max-height: 80px;
  overflow-y: auto;
}

.staff-name {
  font-size: 14px;
  color: #42b983;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 弹窗样式 */
.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.popup-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.staff-list-container {
  padding: 15px;
  max-height: calc(100% - 120px);
  overflow-y: auto;
}

.staff-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  margin-bottom: 10px;
  background: #f8f8f8;
  border-radius: 8px;
  transition: all 0.3s;
}

.staff-item:hover {
  background: #f0f0f0;
}

.staff-item.selected {
  background: #e6f7f0;
  border: 1px solid #42b983;
}

.staff-info {
  display: flex;
  align-items: center;
}

.staff-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #42b983;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 15px;
}

.staff-details .staff-name {
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.staff-details .staff-position {
  font-size: 12px;
  color: #666;
}

.popup-footer {
  padding: 15px;
  border-top: 1px solid #eee;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .calendar-grid {
    gap: 5px;
  }

  .calendar-day {
    padding: 5px;
    min-height: 100px;
  }

  .staff-name {
    font-size: 12px;
  }
}
</style>
